# encoding=utf-8
import os
import xlwt
from xlwt.Worksheet import Worksheet
import time

path = r'要转化的文件夹根目录'
file_dicts = {}

# 将目录名、文件名读取为字典数据
def find_dir_name(path,key=''):
    file_names = os.listdir(path)
    file_dict = {}
    for file_name in file_names:
        print('当前目录：%s' % path+'\\'+file_name)
        file_dict[file_name] = {}
        if os.path.isdir(path+'\\'+file_name):
            file_dict[file_name] = find_dir_name(path+'\\'+file_name, file_name)
        else:
            pass
    return file_dict




# 将字典数据存入Excel
def edit_excel(worksheet,data):
    # 遍历字典数据
    global row_number, row_data
    for key,value in data.items():
        if value:
            row_data.append(key)
            # 如果value有值，则进行一次遍历
            edit_excel(worksheet,value)
        else:
            # 若value值为空，则将key写入sheet
            # 进行写入excle
            col = 0
            for name in row_data:
                print('位置：%d，%d；值：%s' % (row_number,col,name))
                worksheet.write(row_number,col,name)
                col = col+1
            print('位置：%d，%d；值：%s' % (row_number,col,name))
            worksheet.write(row_number,col,key)
            row_number = row_number+1
    if row_data:
        row_data.pop()
    # time.sleep(1)
    return True

if __name__ == '__main__':
    # mm = str(find_dir_name(path,key))
    # f = open('file_name.txt', 'wb')
    # f.write(mm.encode('utf-8'))
    # f.close()
    data = find_dir_name(path)
    # 创建工作表
    workbook = xlwt.Workbook(encoding='utf-8')
    worksheet = workbook.add_sheet('sheet1',cell_overwrite_ok=True)
    # 临时记录一行数据
    row_data = []
    row_number = 0
    edit_excel(worksheet,data)
    workbook.save('转化后的excel文件名称.xls')
